package server

import (
	"context"
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"

	"gorm.io/gorm"
	"longmen/server/pkg/common/api_models"
)

func (s *Server) ContributeRank(ctx context.Context, req *pb.ContributeRankReq) (*pb.ContributeRankResp, error) {
	resp, err := s.GetContributeRank(ctx, req)
	if err != nil {
		return nil, err
	}
	return &pb.ContributeRankResp{ContributeRank: resp}, nil
}

// 目前只是统计diamond
func (s *Server) GetContributeRank(ctx context.Context, r *pb.ContributeRankReq) ([]*pb.ContributeRank, error) {
	cacheKey := "ContributeRank" + fmt.Sprintf("%d%d", r.Anchorid, r.Type)
	var start, end time.Time

	resp := make([]*pb.ContributeRank, 0)

	cache.GetCachedData(cacheKey, &resp)
	if len(resp) > 0 {
		return resp, nil
	}

	//日榜单
	if r.Type == 0 {
		start, end = time2.GetTodayDateTime()
	} else {
		//周榜单
		start, end = time2.GetWeekStartAndEndWithTimeStamp()
	}
	contributes, err := GetGiftLogSumsParam(map[string]interface{}{
		"anchorid":    r.Anchorid,
		"spend_type":  _const.CoinDiamond,
		"create_time": map[string]interface{}{">": start, "<": end},
	}, "id,uid,anchorid,liveid,(sum(actual_spend)) as intimacy", "uid", "intimacy desc", 0, 5)

	if err != nil {
		return nil, err
	}
	if len(contributes) > 0 {
		tmpIds := make([]int, 0)
		for _, v := range contributes {
			tmpIds = append(tmpIds, v.Uid)
		}
		var userMap []*models_main.PartUser
		if len(tmpIds) > 0 {
			userMap, err = db_main.GetPartUsersParam(map[string]interface{}{"id": map[string]interface{}{"in": tmpIds}}, "", 0, 0)
			if err != nil {
				return nil, err
			}
		}
		for _, v := range contributes {
			getContributeRankResp := &pb.User{}
			for _, u := range userMap {
				if u.Id == v.Uid {
					getContributeRankResp.Uid = int32(v.Uid)
					getContributeRankResp.NickName = u.NickName
					getContributeRankResp.Avatar = u.Avatar
					partUser, _ := s.GetLevelAndNoble(u)
					if partUser != nil {
						getContributeRankResp.Level = int32(partUser.Level)
						getContributeRankResp.NobleId = int32(partUser.NobleId)
					} else {
						getContributeRankResp.Level = 0
						getContributeRankResp.NobleId = 0
					}
					break
				}
			}

			resp = append(resp, &pb.ContributeRank{
				Id:       int32(v.Id),
				Uid:      int32(v.Uid),
				Anchorid: int32(v.Anchorid),
				Liveid:   v.Liveid,
				Intimacy: int32(v.Intimacy / 100), // 贡献除以10显示
				User:     getContributeRankResp,
			})

		}
		cache.SetCacheData(cacheKey, resp, 20*time.Second)
	}

	return resp, nil
}

func GetGiftLogSumsParam(param map[string]interface{}, selectCol, groupBy, order string, page, size int) ([]*api_models.GiftLog, error) {
	o := make([]*api_models.GiftLog, 0)
	table := global.GetR().Model(&models_main.GiftLog{})
	table.Select(selectCol)
	Condition(table, param, groupBy, order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o, err
}

func GetSendGiftSum(param map[string]interface{}, column string) (int64, error) {
	o := &Total{}
	table := global.Live().Model(&models_main.GiftLog{})
	Condition(table, param, "", "", 0, 0)
	err := table.Select(fmt.Sprintf("sum(%s) as s", column)).Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o.S, err
}
